﻿Imports System.IO
Imports System.Text.RegularExpressions
Imports Microsoft.Office.Interop.Excel

Public Class CacheOperation
    Implements IDisposable
    Friend Form1
    Friend InputParser
    'Public Shared types As New HashSet(Of String)({"Вакси_грузовая", "Вакси_легковая", _
    '                                                 "Вася", "Гранат", "Кама_Алтай", "Кама_Кама", _
    '                                                 "Мотопарк", "Олег", "Опт", "Покрышкино", _
    '                                                 "Римбат", "СтартШина", _
    '                                               "Диски_Опт", "Диски_Гранат", "Диски_Покрышкино"})
    Public Shared types As New HashSet(Of String)({"Опт"})
    Protected Friend cachedir As DirectoryInfo
    Protected Friend cachepath As String
    Private ex As Application
    Private texterrfile As String
    Private textfile As String
    Private succs_global As List(Of SuccObject)
    Private succs_fromcodes_global As List(Of SuccObject)
    Private err_global As List(Of String)
    Dim bin_arr() As Byte
    Sub Dispose() Implements IDisposable.Dispose
        Try
            ex.Quit()
        Catch ex As Exception
        Finally
            ex = Nothing
        End Try
    End Sub
    Sub RebuildCacheList()
        My.Forms.Form1.CachedTypes.Clear()
        For Each cfile As FileInfo In cachedir.EnumerateFiles("*.csv")
            Dim n As String = Regex.Replace(cfile.Name, "^(.*)\.csv$", "$1")
            Dim d As Date = cfile.LastWriteTime
            If (types.Contains(n)) Then
                My.Forms.Form1.CachedTypes.Add(New CachedTypeObject(n, d.ToString("dd.MM.yy")))
            End If
        Next cfile
    End Sub
    Sub New()
        succs_fromcodes_global = New List(Of SuccObject)
        My.Forms.Form1.TypesBindingSource.DataSource = types
        cachepath = Directory.GetCurrentDirectory() + "\cache\"
        cachedir = Directory.CreateDirectory(cachepath)
        RebuildCacheList()

    End Sub
    Public Sub commit()

        Dim processed_set As New HashSet(Of String)

        Dim workdir As String = Directory.GetCurrentDirectory()
        Dim temp As String = Path.GetTempFileName
        Dim template = workdir + "\" + "template.xlt"
        ex.DisplayAlerts = False
        'Dim resWB As Workbook
        'resWB = ex.Workbooks.Open(template)




        Dim linecount As Integer = 0
        'Dim discs As New List(Of String)
        For Each f As FileInfo In cachedir.EnumerateFiles
            'If Regex.IsMatch(f.Name, "^Диски") Then
            '    discs.AddRange(File.ReadAllLines(f.FullName, Encoding1251))
            'Else
            Dim s As String() = File.ReadAllLines(f.FullName, Encoding1251)
            linecount = linecount + s.Count
            File.AppendAllLines(temp, s, Encoding1251)
            'End If
        Next f
        If linecount <> 0 Then
            Dim allWB As Workbook = ex.Workbooks.Open(temp, Format:=2)
            Dim src As Worksheet = allWB.ActiveSheet ' Format:=2 means commas (,) as delimiters, see msdn

            succs_global = extractText(src, False)


            'Dim res As Worksheet = resWB.Sheets(RESULT_SHEET_NAME_TIRES)
            'src.UsedRange.Copy()
            'res.Cells(2, 1).PasteSpecial(XlPasteType.xlPasteValues)
            'hide away
            'res.Columns(Variables.RESULT_AVAIL_COLUMN).Delete(Shift:=XlDeleteShiftDirection.xlShiftToLeft)

            'ExcelOps.getColumn(src, 14, linecount).FormulaR1C1 = "=RC[-3]-RC[-4]" ' 14.delta formula
            'ExcelOps.getColumn(src, 12, linecount).FormulaR1C1 = "=RC[-1]*" + DoubleToExcelString(NDS_COEFF) + "*" + BYR_USD_CONV.ToString ' 12.opt+NDS formula
            src = Nothing
            'res = Nothing
            allWB.Close()
            allWB = Nothing
        End If


        'If discs.Count > 0 Then
        '    commitDiscs(resWB, discs)
        'End If

        'succs_global.AddRange(succs_fromcodes_global)


        'Try
        '    File.AppendAllLines(texterrfile, err_global, Encoding1251)
        'Catch exc As IOException
        '    MsgBox("Ошибка ввода-вывода при попытке записи в файл:" + texterrfile)
        'End Try

        Try
            If Not textfile Is Nothing Then
                File.AppendAllLines(textfile, succOut(succs_global))
                bin_arr = File.ReadAllBytes(textfile)
            End If
        Catch exc As IOException
            MsgBox("Ошибка ввода-вывода при попытке записи в файл:" + textfile)
        End Try

        'With My.Forms.Form1.ExcelSaveDialog
        '    '.Reset()
        '    .FileName = EXPORT_EXCEL_DEFAULT_FILENAME
        '    If (.ShowDialog() = DialogResult.OK) Then
        '        Dim fileformat As Object
        '        If (Regex.IsMatch(.FileName, "\.xls$")) Then
        '            fileformat = XlFileFormat.xlExcel8
        '        Else
        '            fileformat = XlFileFormat.xlExcel12
        '        End If
        '        resWB.SaveAs(Filename:=.FileName, FileFormat:=fileformat)
        '        resWB.Close()
        '        ex.DisplayAlerts = True
        '        ex.ScreenUpdating = True
        '        ex.Quit()
        '    Else
        '        ex.ScreenUpdating = True
        '        ex.DisplayAlerts = True
        '        ex.Visible = True
        '        ex.UserControl = True
        '    End If
        'End With
        ex.Quit()
        'resWB = Nothing
        ex = Nothing

        File.Delete(temp)
    End Sub
    Sub initExcel()
        ex = New Application
        ex.DisplayAlerts = False
        ex.ScreenUpdating = False
        ex.Visible = False
    End Sub
    Sub cache(textfile As String, texterrfile As String)
        initExcel()

        Dim cached As New SortedDictionary(Of String, CachedTypeObject)
        Me.textfile = textfile
        Me.texterrfile = texterrfile

        Dim inp_parser As InputParser
        inp_parser = New InputParser(cachepath, ex)
        With My.Forms.Form1
            For Each o As CachedTypeObject In .CachedTypes ' populate dict 
                Try
                    cached.Add(o.type, o)
                Catch x As Exception
                End Try
            Next
            For Each item As GridObject In .CurrentItems

                If (cached.ContainsKey(item.type)) Then ' if type is in list of cached, override - delete cache and remove from list
                    .CachedTypes.Remove(cached.Item(item.type))
                    Try
                        cachedir.GetFiles(item.type + ".csv").Single.Delete()
                    Catch x As Exception
                    End Try
                End If

                If (item.path Is Nothing Or item.path = "") Then
                    MsgBox("Файл прайса для типа " + item.type + "не существует")
                    Exit Sub
                End If

                If Not (File.Exists(item.path)) Then
                    MsgBox("Файл " + item.path + " не существует")
                    Exit Sub
                End If

                'If Not (item.matchfile Is Nothing Or item.matchfile = "") Then
                '    If Not File.Exists(item.matchfile) Then
                '        MsgBox("Файл " + item.matchfile + " не существует")
                '        Exit Sub
                '    End If
                'End If

                inp_parser.parse(item) ' insert new one in cache

            Next item
        End With
        RebuildCacheList()

        err_global = inp_parser.err_global
        'succs_fromcodes_global = inp_parser.succs_global_fromcodes
        inp_parser.kill()


        inp_parser = Nothing
    End Sub

    Sub clearcache()
        For Each f As FileInfo In cachedir.GetFiles()
            Try
                f.Delete()
            Catch ex As IOException
                MsgBox("Невозможно удалить файл из кэша - " + f.FullName + ".")
                Exit Sub
            End Try
        Next

        RebuildCacheList()
    End Sub

    Private Function extractText(src As Worksheet, discs As Boolean) As List(Of SuccObject)
        Dim sitecode, price, avail, quantity, type
        Dim i As Integer
        Dim l As New List(Of SuccObject)
        Dim count As Integer = src.Columns(1).CurrentRegion.Rows.Count
        sitecode = ExcelOps.getColumn(src, RESULT_SITECODE_COLUMN, count).Value
        avail = ExcelOps.getColumn(src, RESULT_AVAIL_COLUMN, count).Value

        'If discs Then
        '    quantity = ExcelOps.getColumn(src, 9, count).Value
        '    price = ExcelOps.getColumn(src, 13, count).Value
        '    type = ExcelOps.getColumn(src, 16, count).Value
        'Else
        quantity = ExcelOps.getColumn(src, 9, count).Value
        price = ExcelOps.getColumn(src, 11, count).Value
        type = ExcelOps.getColumn(src, 13, count).Value
        'End If

        For i = 1 To count
            If Not sitecode(i, 1) Is Nothing Then
                If sitecode(i, 1).ToString <> sitecode_null Then
                    l.Add(New SuccObject(sitecode(i, 1) _
                                         , MatchParser.productAvailable(quantity(i, 1)) _
                                         , MatchParser.getPrice(price(i, 1)) _
                                         , MatchParser.getQuantity(quantity(i, 1)), type(i, 1)))
                End If
            End If
        Next
        extractText = l
    End Function

    'Private Sub commitDiscs(ByRef resWB As Workbook, ByRef collected As List(Of String))
    '    Dim temp As String = Path.GetTempFileName
    '    Dim res As Worksheet = resWB.Sheets(RESULT_SHEET_NAME_DISCS)
    '    File.WriteAllLines(temp, collected, Encoding1251)
    '    Dim discsWB As Workbook = ex.Workbooks.Open(temp, Format:=2)
    '    Dim src As Worksheet = discsWB.ActiveSheet ' Format:=2 means commas (,) as delimiters, see msdn
    '    src.UsedRange.Copy()
    '    res.Cells(2, 1).PasteSpecial(XlPasteType.xlPasteValues)

    '    If succs_global Is Nothing Then
    '        succs_global = extractText(src, True)
    '    Else
    '        succs_global.AddRange(extractText(src, True))
    '    End If

    '    res.Columns(Variables.RESULT_AVAIL_COLUMN).Delete(Shift:=XlDeleteShiftDirection.xlShiftToLeft)
    '    ExcelOps.getColumn(res, 14, startrow:=2).FormulaR1C1 = "=RC[-1]-RC[-2]" ' 14.delta formula
    '    src = Nothing
    '    res = Nothing
    '    discsWB.Close()
    '    discsWB = Nothing
    '    File.Delete(temp)
    'End Sub

    Sub send()
        'Dim request As Net.HttpWebRequest = Net.HttpWebRequest.Create(POST_SITE_URL)
        'request.Method = "POST"
        'request.ContentLength = bin_arr.Length
        'request.ContentType = "text/plain"
        'Dim stream As IO.Stream = request.GetRequestStream()
        'stream.Write(bin_arr, 0, bin_arr.Length)
        'Dim response As Net.HttpWebResponse = request.GetResponse
        'response.Close()
        Using wc As New System.Net.WebClient()
            wc.UploadFile(POST_SITE_URL, textfile)
        End Using
    End Sub


End Class
